<?php

class ScoreboardsController extends AppController {
	var $uses=array("Scoreboard","Problem","User");
	var $scaffold = 'admin';
	function index(){
		try{
			if(!$this->Session->read('Auth.User')) {
				throw new Exception('Not logged in');
			}
			$userid=$this->Auth->user('id');
			$result=$this->Scoreboard->find('all',array('fields'=>array('Scoreboard.user_id','SUM(`Scoreboard`.`point`) AS `point`','SUM(`Scoreboard`.`penalty`) AS `penalty`',"User.username","User.id"),'group'=>array('user_id'),'order'=>array('point DESC','penalty DESC')));
			$this->set('scoreboard',array("success"=>1,"scoreboard"=>$result));
		}catch(Exception $e){
			$this->set('scoreboard',array("success"=>0,"errmsg"=>$e->getMessage()));
		}
		$this->set('json',array('scoreboard'));
	}
	/*
	 * user_scoreboard() - returns scoreboard of users.
	 *
	 * data:
	 *
	 * Null
	 *
	 * return:
	 *
	 * scoreboard[] : json object of user list(sorts by score).
	 *
	 */

	function user_scoreboard($id=null){
		try{
			if (!$this->Session->read('Auth.User')) {
				throw new Exception("Not logged in");
			}
			$user=$this->Auth->user();
			if($id==null){
				$id=$user["User"]["id"];
			}
			$data=$this->Scoreboard->findAllByUserId($id);
			$this->set('scoreboard',$data);
			$this->set('json',array("scoreboard"));
		}catch(Exception $exception){
			$this->set('scoreboard',array("success"=>0,"errmsg"=>$exception->getMessage()));
			$this->set('json',array("scoreboard"));
		}
	}

	/*
	 * question_scoreboard($id) - returns the scoreboard of a question.
	 *
	 * data:
	 *
	 * [GET] id : id of question.
	 *
	 * return:
	 *
	 * scores[] : json object of scoreborad.
	 *
	 */

	function question_scoreboard($id=null){
		try{
			if($id==null){
				$data=$this->Scoreboard->find("all");
				$this->set('scoreboard',$data);
				$this->set('json',array("scoreboard"));
				$this->render();
			}
			$data=$this->Scoreboard->findAllByProblemId($id);
			$this->set('scoreboard',$data);
			$this->set('json',array("scoreboard"));
			$this->render();
		}catch(Exception $exception){
			$this->set('scoreboard',array("success"=>0,"errmsg"=>$exception->getMessage()));
			$this->set('json',array("scoreboard"));
		}
	}
}
?>
